package com.demo.user;

import java.io.File;

import org.nature.framework.annotation.Ask;
import org.nature.framework.annotation.Ctrl;
import org.nature.framework.annotation.Inject;
import org.nature.framework.annotation.Interceptors;
import org.nature.framework.annotation.Redirect;
import org.nature.framework.annotation.Validator;
import org.nature.framework.core.NatureCtrl;
import org.nature.framework.util.FileUtil;
import org.nature.framework.util.StringUtil;

/**
 * 用户控制层
 * 
 * 1、创建控制层继承NatureCtrl类并增加@Ctrl注解即可
 * <p>
 * 2、类@Ctrl的namespace是控制层的命名空间，所有本控制层的请求都要通过namespace
 * <p>
 * 3、属性@Inject注解是注入Service实例
 * <p>
 * 4、方法@Ask注解是对方法的映射，如果不写url则默认映射为方法名；与namespace共同组成请求路径/namespace/list
 * <p>
 * 5、返回支持直接返回页面"xxx.jsp",返回方法"xxx",返回JSON数据 JsonData,返回下载文件FileData等，绝对的简单快捷
 * <p>
 * 6、在控制层需要页面传值的只需声明public类型变量即可，无需冗长的GET/SET
 * <p>
 * 7、如需上传文件，控制层直接声明File类型变量即可，支持多文件集合上传，就像接受普通变量一样简单
 * <p>
 * 
 */
@Ctrl(namespace="/user")
@Interceptors(UserInterceptor.class)
public class UserCtrl extends NatureCtrl{
	private static final long serialVersionUID = 1L;
	
	public File headpic;
	public User user ;
	public String ask;
	
	@Inject
	UserService userService;
	
	@Ask
	public Object list(){
		String sql="select * from tb_user";
		userService.page(page, sql);
		return "list.ftl";
	}
	
	@Ask
	public Object toOper() {
		if (user!=null) {
			userService.byId(user);
			ask = "update";
		} else {
			ask = "insert";
		}
		return "oper.ftl";
	}
	
	@Ask
	@Validator(UserValidator.class)
	public Object insert(){
		if (headpic!=null) {
			String path = getRealPath()+File.separatorChar+"pics"+File.separatorChar+headpic.getName();
			File file = new File(path);
			user.put(User.headpic, "pics"+File.separatorChar+headpic.getName());
			FileUtil.move(headpic, file);
		}
		userService.insert(user);
		return "list";
	}

	@Ask
	@Validator(UserValidator.class)
	public Object update(){//TODO 转发时候带文件出错，也就是说最有可能是cos对request改装后chucuo
		if (headpic!=null) {
			User oldUser = userService.byId(user);
			String oldpath = oldUser.getString(User.headpic);
			if (StringUtil.isNotBank(oldpath)) {
				File f = new File(getRealPath()+oldpath);
				if (f.exists()) {
					f.delete();
				}
			}
			String path = getRealPath()+"pics"+File.separatorChar+headpic.getName();
			File file = new File(path);
			file.getParentFile().mkdirs();
			user.put(User.headpic, "pics"+File.separatorChar+headpic.getName());
			FileUtil.move(headpic, file);
		}
		userService.update(user);
		return "list";
	}

	@Ask
	@Redirect
	public Object delete() {
		user = userService.byId(user);
		String path = user.getString(User.headpic);
		if (StringUtil.isNotBank(path)) {
			File file = new File(path);
			if (file.exists()) {
				file.delete();
			}
		}
		userService.delete(user);
		return "list";
	}
}
